#!/bin/bash
function install_apache() {
    echo -e "${blue}当前正在执行的操作为:${nocolor} ${green}安装apache${nocolor}"
    echo ""
    apachePid=`pidof httpd`
    if [ -n "$apachePid" ];then
        echo -e "$Warn 系统已有正在运行中的Apache，请删除后继续!"
        anykeyback
        return 1
    fi
    
    echo -ne "输入需要安装的Apache版本[2.4.43]: "
    read apacheVer
    apacheVer=${apacheVer:-2.4.43}
    apacheVer=`echo $apacheVer`
    echo ""
    
    if [ ! -f $workHome/packages/apache/httpd-$apacheVer.tar.bz2 -a "$die_network" == "ture" ];then
        echo -ne "$Error 系统未联网，且本地不存在需要安装的Apache版本, 退出！"
        anykeyback
        return 1
    fi
    
    echo -ne "输入Apache安装位置[/usr/local/apache2]: "
    read -e apachePath
    apachePath=${apachePath:-/usr/local/apache2}
    apachePath=`echo ${apachePath}`
    apachePath=${apachePath%/}
    echo ""
    
    isNull=`ls $apachePath/* 2>/dev/null | wc -l`
    if [[ $isNull -gt 0 ]];then
        echo -ne "Apache安装目录非空，继续安装会删除已有数据！\n继续[Yy,Enter],退出[Nn]: "
        read isYn
        if [[ $isYn == [Nn] ]];then
           sleep 0.5
           return 1
        fi
        echo ""
    fi
    
    command -v ss >/dev/null 2>&1
    if [ "$?" == "0" ];then
        listen_cmd="ss -lnpt"
    else
        command -v netstat >/dev/null 2>&1
        if [ "$?" == "0" ];then
          listen_cmd="netstat -tnlp"
        fi
    fi
    [[ $listen_cmd ]] && PortCheck=Yes || PortCheck=No
    PortUsed=
    PortUsed_Pro=
    apachePort=
    while [[ ! "$apachePort" =~ ^[1-9][0-9]+$ || "$PortUsed" == "Yes" ]]
    do
        echo -ne "请输入Aapche监听端口[80]: "
        read apachePort
        apachePort=${apachePort:-80}
        if [[ ! "$apachePort" =~ ^[1-9][0-9]+$ ]];then
            echo -e "$Warn Apache端口只能为两位及以上且不以0开头的数字组成，请重新输入！"
            sleep 0.1
        else
            if [ "$PortCheck" == "Yes" ];then
                PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${apachePort} "`
                if [ -n "$PortUsed_Pro" ];then
                  PortUsed=Yes
                  echo -e "$Warn Apache端口已被使用，请重新输入！"
                else
                  PortUsed=No
                fi
            else
                PortUsed=No
            fi
        fi
    done
    echo ""

    echo -ne "${blue}Apache安装信息汇总${nocolor}
---------------------------------
Apache版本：$apacheVer
Apache安装位置：$apachePath
Apache端口：$apachePort
---------------------------------
继续[Yy,Enter],退出[Nn]: "
    read isYn
    [[ $isYn != [Nn] ]] || { sleep 0.5;return 1; }
    
    echo ""
    apacheHome="$workHome/packages/apache"
    cd $apacheHome
   
    echo -e "${cyan}将开始apache安装过程${nocolor}"
    echo ""
    if [ "$die_network" == "true" ];then
        ping -c 2 -w 5 180.76.76.76 >/dev/null 2>&1
        if [ "$?" != "0" ];then
           die_network="true"
        else
           die_network="false"
        fi
    fi
    if [[ ! -f ${apacheHome}/httpd-${apacheVer}.tar.bz2 && "$die_network" == "false" ]];then
        echo -e "$Info ${purple}下载apache安装包${nocolor}"
        curl --progress-bar --connect-timeout 30 -m 360 --fail -O https://mirrors.huaweicloud.com/apache/httpd/httpd-$apacheVer.tar.bz2
        if [ "$?" != "0" ];then
            rm -rf ${apacheHome}/httpd-${apacheVer}.tar.bz2
            curl --progress-bar --connect-timeout 30  -m 480 --fail -O https://archive.apache.org/dist/httpd/httpd-$apacheVer.tar.bz2
        fi   
        if [ "$?" != "0" ];then
           echo -e "$Error 下载apache失败，请检查网络或者不存在此版本的Apache！！！"
           anykeyback
           return 1
        fi
    elif [[ ! -f ${apacheHome}/httpd-${apacheVer}.tar.bz2 && "$die_network" == "true" ]];then
        echo -e "$Error 你的主机未联网，请提前手动下载安装包，使用离线安装！！！"
        anykeyback
        return 1
    fi
    
    echo -e "$Info ${purple}安装所需基础RPM包${nocolor}"
    yum -y install make gcc gcc-c++ aprutil aprutil-devel openldap openldap-devel apr apr-util-ldap lynx mailcap apr-devel expat-devel bzip2 libtool libtool-ltdl libtool-ltdl-devel libcurl libcurl-devel jansson jansson-devel nghttp2 nss nss-devel openssl openssl-devel glibc glibc-devel automake
    if [ "$?" != "0" ];then
        echo -e "$Error 基础依赖软件安装失败，退出安装！！！"
        anykeyback
        return 1
    fi
    for i in make gcc gcc-c++ openssl openssl-devel libcurl libcurl-devel apr apr-devel libtool glibc glibc-devel automake
    do
        rpm -q $i >/dev/null 2>&1
        if [ "$?" != "0" ];then
            echo -e "$Error 基础依赖软件${i}安装失败，退出安装！！！"
            anykeyback
            return 1
        fi
    done
    
    find $apacheHome/* -type d|xargs rm -rf
    cd $apacheHome
    echo -e "${blue}安装apr${nocolor}"
    aprPack=`ls -r |grep apr-[0-9]|head -n 1`
    if [ -z "$aprPack" ];then
        echo -e "$Info ${purple}下载apr${nocolor}"
        curl --progress-bar --connect-timeout 30 -m 360 --fail -O https://mirrors.tuna.tsinghua.edu.cn/apache/apr/apr-1.7.0.tar.bz2
        download_status=$?
    fi
    if [ "${download_status}" != "0" ];then
        rm -rf apr-1.7.0.tar.bz2
        curl --progress-bar --connect-timeout 30 -m 360 --fail -LkO https://gitee.com/ElvisTan/software-house/attach_files/974551/download/apr-1.7.0.tar.bz2
        download_status=$?
    fi
    
    if [ "${download_status}" != "0" ];then
        echo -e "$Error apr下载失败，退出安装！！！"
        rm -rf apr-1.7.0.tar.bz2
        anykeyback
        return 1
    fi
    
    aprPack=`ls -r |grep apr-[0-9]|head -n 1`
    apruPack=${aprPack%.tar*}
    echo -e "$Info ${purple}解压apr${nocolor}"
    echo $aprPack|grep ".tar.gz">/dev/null && tar zxf $aprPack ||tar jxf $aprPack && \
    cd $apruPack && \
    echo -e "$Info ${purple}预编译apr${nocolor}" && \
    ./configure --prefix=/usr/local/apr && \
    echo -e "$Info ${purple}编译apr${nocolor}" && \
    make -j8 && \
    echo -e "$Info ${purple}安装apr${nocolor}" && \
    make install
    if [ "$?" != "0" ];then
        echo -e "$Error 安装apr失败，退出安装！！！"
        anykeyback
        return 1
    fi
    echo " ">>$logs_file
    echo " ">>/tmp/apache-comp.log
    
    echo -e "${blue}安装apr-util${nocolor}"
    cd $apacheHome
    aprutilPack=`ls -r |grep apr-util|head -n 1`
    if [ -z "$aprutilPack" ];then
        echo -e "$Info ${purple}下载apr-util$nocolor"
        curl --progress-bar --connect-timeout 30 -m 360 --fail -O https://mirrors.tuna.tsinghua.edu.cn/apache//apr/apr-util-1.6.1.tar.bz2
        download_status=$?
    fi
    if [ "${download_status}" != "0" ];then
        rm -rf apr-util-1.6.1.tar.bz2
        curl --progress-bar --connect-timeout 30 -m 360 --fail -LkO https://gitee.com/ElvisTan/software-house/attach_files/974550/download/apr-util-1.6.1.tar.bz2
        download_status=$?
    fi
    
    if [ "${download_status}" != "0" ];then
        echo -e "$Error apr-util下载失败，退出安装！！！"
        rm -rf apr-util-1.6.1.tar.bz2
        anykeyback
        return 1
    fi
    
    aprutilPack=`ls -r |grep apr-util|head -n 1`
    aprutiluPack=${aprutilPack%.tar*}
    echo -e "$Info ${purple}解压apr-util${nocolor}"
    echo $aprutilPack|grep ".tar.gz">/dev/null && tar zxf $aprutilPack ||tar jxf $aprutilPack && \
    cd $aprutiluPack && \
    echo -e "$Info ${purple}预编译apr-util${nocolor}" && \
    ./configure --prefix=/usr/local/apr-util --with-ldap --with-crypto --with-apr=/usr/local/apr/bin/apr-1-config && \
    echo -e "$Info ${purple}编译apr-util${nocolor}" && \
    make -j8 && \
    echo -e "$Info ${purple}安装apr-util${nocolor}" && \
    make install
    if [ "$?" != "0" ];then
        echo -e "$Error 安装apr-util失败，退出安装！！！"
        anykeyback
        return 1
    fi
  
    echo -e "${blue}安装pcre${nocolor}"
    cd $apacheHome
    pcrePack=`ls -r |grep pcre|head -n 1`
    ngPcrePack=`ls -r $workHome/packages/nginx/ 2>/dev/null|grep pcre|head -n 1`
    if [ -z "$pcrePack" ];then
        if [ -z "$ngPcrePack" ];then
           echo -e "$Info ${purple}下载PCRE${nocolor}"
           curl --progress-bar --connect-timeout 30 -m 360 --fail -O https://ftp.pcre.org/pub/pcre/pcre-8.44.tar.bz2
           download_status=$?
        else
           echo -e "$Info ${purple}从Nginx安装目录复制Pcre${nocolor}"
           /bin/cp -f $workHome/packages/nginx/$ngPcrePack .
           download_status=$?
        fi
    fi
    if [ "${download_status}" != "0" ];then
        rm -rf pcre-8.44.tar.bz2
        curl --progress-bar --connect-timeout 30 -m 360 --fail -LkO https://gitee.com/ElvisTan/software-house/attach_files/974552/download/pcre-8.44.tar.bz2
        download_status=$?
    fi
    
    if [ "${download_status}" != "0" ];then
        echo -e "$Error pcre下载失败，退出安装！！！"
        rm -rf pcre-8.44.tar.bz2
        anykeyback
        return 1
    fi
    
    pcrePack=`ls -r |grep pcre|head -n 1`
    pcreuPack=${pcrePack%.tar*}
    echo -e "$Info ${purple}解压pcre${nocolor}"
    echo $pcrePack|grep ".tar.gz">/dev/null && tar zxf $pcrePack ||tar jxf $pcrePack && \
    cd $pcreuPack && \
    echo -e "$Info ${purple}预编译Pcre${nocolor}" && \
    ./configure --prefix=/usr/local/pcre &&\
    echo -e "$Info ${purple}编译Pcre${nocolor}" && \
    make -j8 && \
    echo -e "$Info ${purple}安装Pcre${nocolor}" && \
    make install
    if [ "$?" != "0" ];then
        echo -e "$Error 安装pcre失败，退出安装！！！"
        anykeyback
        return 1
    fi
    
    echo -e "${blue}安装apache${nocolor}"
    rm -rf $apachePath
    cd $apacheHome
    echo -e "$Info ${purple}解压apache${nocolor}"
    tar jxf httpd-${apacheVer}.tar.bz2 && cd httpd-${apacheVer} && \
    echo -e "$Info ${purple}预编译apache${nocolor}" && \
    ./configure --prefix=$apachePath --with-pcre=/usr/local/pcre --with-apr=/usr/local/apr --with-apr-util=/usr/local/apr-util/ --enable-so --enable-dav --enable-ssl --enable-cgi --enable-rewrite --with-zlib --enable-modules=most --enable-mpms-shared=all --with-mpm=event && \
    echo -e "$Info ${purple}编译apache${nocolor}" && \
    make -j8 && \
    echo -e "$Info ${purple}安装apache${nocolor}" && \
    make install
    if [ "$?" != "0" ];then
        echo -e "$Error 安装apache失败，退出安装！！！"
        anykeyback
        return 1
    fi

    echo -e "$Info ${purple}创建apache运行用户apache${nocolor}"
    cat /etc/passwd|grep "^apache:" >/dev/null
    if [ "$?" != "0" ];then
        useradd -M -s /sbin/nologin apache>>$logs_file 2>&1
    else
        userdel -f apache >/dev/null
    fi
    
    echo -e "$Info ${purple}修改apache配置${nocolor}"
    sed -i "/^#ServerName www.example.com:80/a ServerName localhost:$apachePort" $apachePath/conf/httpd.conf
    sed -i 's/^User.*/User apache/g' $apachePath/conf/httpd.conf
    sed -i 's/^Group.*/Group apache/g' $apachePath/conf/httpd.conf
    sed -i "/AddType application\/x-gzip .gz .tgz/a     AddType application\/x-httpd-php .php" $apachePath/conf/httpd.conf
    sed -i "/AddType application\/x-gzip .gz .tgz/a     AddType application\/x-httpd-php-source .phps" $apachePath/conf/httpd.conf
    sed -i 's/DirectoryIndex index.html/DirectoryIndex index.html index.php/g' $apachePath/conf/httpd.conf
    sed -i "s/^Listen 80/Listen $apachePort/g" $apachePath/conf/httpd.conf
    cat >$apachePath/htdocs/phpinfo.php<<'EOF'
<?php
phpinfo();
?>
EOF

    chown -R apache:apache $apachePath >/dev/null
    
    echo -e "$Info ${purple}配置apache服务脚本，并启动${nocolor}"
    if [[ $system_ver != [456] ]];then
        cat >/etc/systemd/system/httpd.service<<EOF
[Unit]
Description=The Apache HTTP Server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
ExecStart=$apachePath/bin/apachectl -k start
ExecReload=$apachePath/bin/apachectl -k graceful
ExecStop=$apachePath/bin/apachectl -k graceful-stop
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF
        chmod 755 /etc/systemd/system/httpd.service >/dev/null 2>&1
        systemctl daemon-reload
        systemctl enable httpd >/dev/null 2>&1
        systemctl start httpd
    else
        cat >/etc/init.d/httpd<<'EOF'
#!/bin/bash
#
# httpd        Startup script for the Apache HTTP Server
#
# chkconfig: - 85 15
# description: The Apache HTTP Server is an efficient and extensible  \
#           server implementing the current HTTP standards.

# Source function library.
. /etc/rc.d/init.d/functions

# Start httpd in the C locale by default.
HTTPD_LANG=${HTTPD_LANG-"C"}

# This will prevent initlog from swallowing up a pass-phrase prompt if
# mod_ssl needs a pass-phrase from the user.
INITLOG_ARGS=""

# Path to the apachectl script, server binary, and short-form for messages.
apachectl=$apachePath/bin/apachectl
httpd=$apachePath/bin/httpd
prog=httpd
pidfile=$apachePath/logs/httpd.pid
lockfile=${LOCKFILE-/var/lock/subsys/httpd}
RETVAL=0
STOP_TIMEOUT=${STOP_TIMEOUT-10}

# The semantics of these two functions differ from the way apachectl does
# things -- attempting to start while running is a failure, and shutdown
# when not running is also a failure.  So we just do it the way init scripts
# are expected to behave here.
start() {
        echo -n $"Starting $prog: "
        LANG=$HTTPD_LANG daemon --pidfile=${pidfile} $httpd $OPTIONS
        RETVAL=$?
        echo
        [ $RETVAL = 0 ] && touch ${lockfile}
        return $RETVAL
}

# When stopping httpd, a delay (of default 10 second) is required
# before SIGKILLing the httpd parent; this gives enough time for the
# httpd parent to SIGKILL any errant children.
stop() {
    status -p ${pidfile} $httpd > /dev/null
    if [[ $? = 0 ]]; then
        echo -n $"Stopping $prog: "
        killproc -p ${pidfile} -d ${STOP_TIMEOUT} $httpd
    else
        echo -n $"Stopping $prog: "
        success
    fi
    RETVAL=$?
    echo
    [ $RETVAL = 0 ] && rm -f ${lockfile} ${pidfile}
}

reload() {
    echo -n $"Reloading $prog: "
    if ! LANG=$HTTPD_LANG $httpd $OPTIONS -t >&/dev/null; then
        RETVAL=6
        echo $"not reloading due to configuration syntax error"
        failure $"not reloading $httpd due to configuration syntax error"
    else
        # Force LSB behaviour from killproc
        LSB=1 killproc -p ${pidfile} $httpd -HUP
        RETVAL=$?
        if [ $RETVAL -eq 7 ]; then
            failure $"httpd shutdown"
        fi
    fi
    echo
}

# See how we were called.
case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  status)
        status -p ${pidfile} $httpd
    RETVAL=$?
    ;;
  restart)
    stop
    start
    ;;
  condrestart|try-restart)
    if status -p ${pidfile} $httpd >&/dev/null; then
        stop
        start
    fi
    ;;
  force-reload|reload)
        reload
    ;;
  graceful|help|configtest|fullstatus)
    $apachectl $@
    RETVAL=$?
    ;;
  *)
    echo $"Usage: $prog {start|stop|restart|condrestart|try-restart|force-reload|reload|status|fullstatus|graceful|help|configtest}"
    RETVAL=2
esac

exit $RETVAL
EOF
        sed -i "s#\$apachePath#$apachePath#g" /etc/init.d/httpd
        chmod 755 /etc/init.d/httpd >/dev/null 2>&1
        chkconfig --add httpd
        chkconfig --level 2345 httpd on
        service httpd start
    fi
    

    echo -e "$Info ${purple}检查apache服务是否运行正常${nocolor}"
    apachePid=`pidof httpd`
    if [ -z "$apachePid" ];then
        $apachePath/bin/apachectl start >/dev/null 2>&1
        sleep 1
        apachePid=`pidof httpd`
        if [ -z "$apachePid" ];then
          echo -e "$Error apache启动失败，检查配置文件及端口是否被占用！！！"
        else
          echo -e "$Warn apache安装完成，但服务脚本无法控制apache服务启停，请检查服务脚本！！！"
        fi
    else
        apacheVer=`$apachePath/bin/apachectl -v|grep "Server version"|grep -o "[0-9.]"|tr -d "\n"`
        [[ "$apachePort" = "80" ]] && requestURL="http://$ipaddr" || requestURL="http://$ipaddr:$apachePort"
        echo -e "$Info ${light_green}apache $apacheVer安装完成${nocolor}
-----------------------------------------------------
你可以通过使用service或systemctl命令来控制apache启停
Nginx安装位置为：$apachePath
请访问 ${blue}$requestURL${nocolor} 检验apache是否运行正常
------------------------------------------------------"
    fi
    anykeyback
}
